package com.revenco.bi.controller;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nutz.lang.Lang;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.revenco.bi.controller.basecontroller.AbstractUserAwareController;
import com.revenco.bi.model.TnChartBaseinfo;
import com.revenco.bi.model.TnChartParams;
import com.revenco.bi.model.userbean.AnychartDataBean;
import com.revenco.bi.model.userbean.OilGaugeBean;
import com.revenco.bi.service.ChartService;
import com.revenco.bi.service.ChartSqlPieceService;
import com.revenco.bi.service.ChartSqlService;
import com.revenco.bi.service.TnChartBaseinfoService;
import com.revenco.bi.service.TnChartDataitemsService;
import com.revenco.bi.service.TnChartParamsService;
import com.revenco.bi.util.Json;

/**
 * 图表操作核心controller类
 * 
 * @author ghq 日期：2014年1月22日11:05:33
 * 
 */
@Controller
public class Chart extends AbstractUserAwareController {
	@Autowired
	private ChartService chartService;
	@Autowired
	private ChartSqlService chartSqlService2;
	@Autowired
	private ChartSqlPieceService chartSqlService;
	@Autowired
	private TnChartBaseinfoService tnChartBaseinfoService;
	@Autowired
	private TnChartDataitemsService tnChartDataitemsService;
	@Autowired
	private TnChartParamsService tnChartParamsService;

	/**
	 * 该方法为指定返回各图表模板页面
	 * 
	 * @param model
	 * @param response
	 * @param chartType
	 * @param strJson
	 * @param cFields
	 * @param xFields
	 * @param yFields
	 * @param mulRelationData
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/chart/showTemplates")
	@ResponseStatus(HttpStatus.OK)
	public String showTemplates(Model model, HttpServletResponse response,
			@RequestParam String chartType, @RequestParam String strJson,
			@RequestParam String cFields, @RequestParam String xFields,
			@RequestParam String yFields, @RequestParam String mulRelationData) throws UnsupportedEncodingException {
		
		String xmlDataInfo = null;
		
		if ("circularGauge".equalsIgnoreCase(chartType)) {
			Map<String, Map<String, String>> map = chartSqlService
					.getSeriesData2(cFields, xFields, yFields, mulRelationData);
			String tempSql = chartSqlService.getOilGaugeBeanSql(yFields, mulRelationData);
			OilGaugeBean oBean = chartService.getOilGaugeBeanInfo(tempSql);
			xmlDataInfo = chartService.getPointersInfo(map, yFields);
			model = chartService.getModelofOilGauge(model, strJson,
					xmlDataInfo, oBean, yFields);
		} else {
			Map<String, List<AnychartDataBean>> map = chartSqlService.getSeriesData(
					cFields, xFields, yFields, mulRelationData);
			xmlDataInfo = chartService.getSeriesData(map, yFields, chartType);
			model = chartService.getModel(model, strJson, xFields, chartType,
					xmlDataInfo, yFields);
		}
		
		response.setContentType("text/xml; charset=utf-8");
		
		String goPage ="";
		if (chartType.equalsIgnoreCase("bar")) {
			goPage = "/anychartTemplates/bar";
		} else if ("bar,Line".equalsIgnoreCase(chartType)) {
			goPage = "/anychartTemplates/barLine";
		} else if ("pie".equalsIgnoreCase(chartType)) {
			goPage = "/anychartTemplates/pie";
		} else if ("spline".equalsIgnoreCase(chartType)) {
			goPage = "/anychartTemplates/line";
		} else if ("circularGauge".equalsIgnoreCase(chartType)) {
			goPage = "/anychartTemplates/oilGauge";
		}

		return goPage;
	}

	/**
	 * 保存图表信息
	 * 
	 * @param chartType
	 * @param strJson
	 * @param xFields
	 * @param yFields
	 * @param cFields
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/chartSave")
	@ResponseStatus(HttpStatus.OK)
	public void save(@RequestParam String chartType,
			@RequestParam String strJson, @RequestParam String cFields,
			@RequestParam String xFields, @RequestParam String yFields,
			@RequestParam String chartId, @RequestParam String dataitemsId,
			@RequestParam String paramId, String mulRelationData) throws Exception {
		// 图表类型
		chartType = new String(chartType.getBytes("ISO8859-1"), "UTF-8");
		// 图形属性集合
		strJson = new String(strJson.getBytes("ISO8859-1"), "UTF-8");
		cFields = new String(cFields.getBytes("ISO8859-1"), "UTF-8");
		xFields = new String(xFields.getBytes("ISO8859-1"), "UTF-8");
		yFields = new String(yFields.getBytes("ISO8859-1"), "UTF-8");

		String sql = chartSqlService.getSql(cFields, xFields, yFields, mulRelationData).getSql();
		String id = chartId.trim();
		if (StringUtils.isEmpty(id)) {
			String newChartId = this.tnChartBaseinfoService.save(strJson,
					chartType, xFields, sql, mulRelationData);
			if (!StringUtils.isEmpty(newChartId.trim())) {
				this.tnChartDataitemsService.save(yFields, chartType,
						newChartId, strJson);
				this.tnChartParamsService.save(cFields, newChartId);
			}
			this.tnChartParamsService.saveTnTableColumnRelation(mulRelationData, newChartId);
		} else {
			this.tnChartBaseinfoService.update(strJson, chartType, xFields,
					sql, id, mulRelationData);
			this.tnChartDataitemsService.update(yFields, chartType, id, strJson);
			this.tnChartParamsService.update(cFields, id);
		}

	}

	@RequestMapping(value = "/list")
	@ResponseStatus(HttpStatus.OK)
	public List<TnChartBaseinfo> list() throws Exception {
		return null;
	}

	/**
	 * url链接直接访问跳转指定jsp页面
	 */
	@RequestMapping(value = "/showChart", produces = "text/plain;charset=UTF-8")
	@ResponseStatus(HttpStatus.OK)
	public String show(Model model, HttpServletRequest request,
			@RequestParam("id") String id) {

		String params = request.getParameter("params");
		model.addAttribute("id", id);
		TnChartBaseinfo chart = tnChartBaseinfoService.getChartinfoById(id);
		model.addAttribute("chartName", chart.getChartTitle());
		model.addAttribute("params", params);
		String mulRelationData = chart.getTableRelationJson();
		if (mulRelationData == null) {
			mulRelationData = "{}";
		}
		model.addAttribute("mulRelationData", mulRelationData);
		return "/chart/show";
	}

	@RequestMapping(value = "/chart/getChartParams", produces = "text/plain;charset=utf-8")
	@ResponseBody
	public String getChartParams(Model model, HttpServletResponse response,
			@RequestParam("chartId") String id) throws Exception {
		List<TnChartParams> tcParamsList = tnChartParamsService
				.getChartParams(id);
		StringBuilder jsonStr = new StringBuilder("");
		jsonStr.append("[");
		TnChartParams tnParams = null;
		for (int i = 0; i < tcParamsList.size(); i++) {
			tnParams = tcParamsList.get(i);
			if (tnParams.getParamType().equals("formalPara")) {
				jsonStr.append("{");
				Json.addProperty(jsonStr, "paramCd", tnParams.getParamCd());
				jsonStr.append(",");
				Json.addProperty(
						jsonStr,
						"paramName",
						tnParams.getParamName().length() > 8 ? tnParams
								.getParamName().substring(0, 8)
								+ "...("
								+ tnParams.getOpType().trim() + ")" : tnParams
								.getParamName()
								+ "("
								+ tnParams.getOpType().trim() + ")");
				jsonStr.append(",");
				Json.addProperty(jsonStr, "defaultValue",
						tnParams.getDefaultValue());
				jsonStr.append(",");
				Json.addProperty(jsonStr, "colType", tnParams.getDataType());
				jsonStr.append(",");
				Json.addProperty(jsonStr, "tableName",
						tnParams.getParamTextvalueFromTableNam());
				jsonStr.append(",");
				Json.addProperty(jsonStr, "paramName2", tnParams.getParamName());
				jsonStr.append("}");
				jsonStr.append(",");
			}
		}
		jsonStr.delete(jsonStr.length() - 1, jsonStr.length()).append("]");
		log.info("jsonStr: {}", jsonStr.toString());
		return jsonStr.toString();
	}

}
